﻿namespace EFMLEditor.Internal.Validating.Attributes
{
    using System;
    using System.Reflection;
    using System.Runtime.CompilerServices;

    public class NotAnonymousAttribute : ValidatingAttribute
    {
        #region Overrides of ValidatingAttribute

        public override bool Do(object inpt, ParameterInfo parameter)
        {
            bool con = !CheckIfAnonymousType(inpt.GetType());

            if (!con)
            {
                this.Message = parameter.Name + " must be anonymous";
            }

            return con;
        }

        private static bool CheckIfAnonymousType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            // HACK: The only way to detect anonymous types right now.
            return IsDefined(type, typeof(CompilerGeneratedAttribute), false)
                && type.IsGenericType && type.Name.Contains("AnonymousType")
                && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
                && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
        }

        #endregion
    }
}